/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.socio.behaviors;

import java.util.Arrays;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.socio.model.User;
import com.socio.utils.FieldLoader.FieldLoaderFields;

/**
 *
 * @author potlow
 */
public class UserUDIDBehavior extends UserBehavior {

    @Override
    public Object read(Object value, List<FieldLoaderFields> fields) {
    	PersistenceManager pm = pmf.getPersistenceManager();
    	
        String UDID;
        if (value instanceof String) {
            UDID = (String) value;
            if (UDID.isEmpty()) {
                throw new IllegalArgumentException("Search string cannot be empty");
            }
        } else {
            throw new IllegalArgumentException("Search value must be a String");
        }

        // check cache first if not there get from db and put into cache
        User user = null;
        if(cache.containsKey(UDID)) {
        	user = (User)cache.get(UDID);
        } else {
        	Query query = null;
        	try {
        		query = pm.newQuery(User.class);
                query.setFilter("androidUDID == androidUDIDParam");
                query.declareParameters("String androidUDIDParam");
        		List<Object> userList = (List<Object>)query.execute(UDID);
        		if(userList.size() == 1)
        			user = (User)userList.get(0);
        		
        		// put user in cache by all its available unique IDs
        		if(user != null) {
        			cache.put(UDID, user);
        			cache.put(user.getKey(), user);
        			if(!user.getFacebookID().isEmpty())
        				cache.put(user.getFacebookID(), user);
        		}
        	} finally {
	            query.closeAll();
	            pm.close();
	        }
        }
        
        return Arrays.asList((Object)user);
    }
}
